<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>智能体管理</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css"
      rel="stylesheet"
    />
    <style>
      .container {
        max-width: 1200px;
        margin: 0 auto;
        background-color: white;
        padding: 30px;
        border-radius: 10px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
      }
      .agent-card {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        transition: all 0.3s ease;
      }
      .agent-card:hover {
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      }
      .btn-primary {
        background-color: #4e73df;
        border-color: #4e73df;
      }
      .btn-primary:hover {
        background-color: #2e59d9;
        border-color: #2e59d9;
      }
      .btn-danger {
        background-color: #e74a3b;
        border-color: #e74a3b;
      }
      .btn-danger:hover {
        background-color: #d52a1a;
        border-color: #d52a1a;
      }
      .modal-content {
        border-radius: 10px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>智能体管理</h2>
        <button class="btn btn-primary" onclick="showAddModal()">
          <i class="bi bi-plus-circle"></i> 添加智能体
        </button>
      </div>

      <div class="row mb-3">
        <div class="col-md-6">
          <div class="input-group">
            <input
              type="text"
              class="form-control"
              id="searchInput"
              placeholder="搜索智能体名称..."
            />
            <button
              class="btn btn-outline-secondary"
              type="button"
              onclick="searchAgents()"
            >
              <i class="bi bi-search"></i>
            </button>
          </div>
        </div>
      </div>

      <div id="agentList" class="row">
        <!-- 智能体列表将通过JavaScript动态加载 -->
      </div>

      <nav aria-label="Page navigation" class="mt-4">
        <ul class="pagination justify-content-center" id="pagination">
          <!-- 分页将通过JavaScript动态加载 -->
        </ul>
      </nav>
    </div>

    <!-- 添加/编辑智能体模态框 -->
    <div class="modal fade" id="agentModal" tabindex="-1">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="modalTitle">添加智能体</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
            ></button>
          </div>
          <div class="modal-body">
            <form id="agentForm">
              <input type="hidden" id="agentId" />
              <div class="mb-3">
                <label for="agentTemplate" class="form-label">智能体模板</label>
                <select
                  class="form-select"
                  id="agentTemplate"
                  onchange="loadTemplate(this.value)"
                >
                  <option value="">请选择模板</option>
                </select>
              </div>
              <div class="mb-3">
                <label for="agentName" class="form-label">智能体名称</label>
                <input
                  type="text"
                  class="form-control"
                  id="agentName"
                  required
                />
              </div>
              <div class="mb-3">
                <label for="agentCode" class="form-label">智能体编码</label>
                <input
                  type="text"
                  class="form-control"
                  id="agentCode"
                  required
                />
              </div>
              <div class="mb-3">
                <label for="systemPrompt" class="form-label">角色设定</label>
                <textarea
                  class="form-control"
                  id="systemPrompt"
                  rows="3"
                  required
                ></textarea>
              </div>
              <div class="mb-3">
                <label for="ttsVoice" class="form-label">设置角色音色</label>
                <div class="input-group">
                  <select class="form-select" id="ttsVoice" required>
                    <option value="">请选择音色</option>
                  </select>
                  <button
                    type="button"
                    class="btn btn-outline-secondary"
                    onclick="previewVoice()"
                  >
                    <i class="bi bi-play-circle"></i> 试听
                  </button>
                </div>
              </div>
              <div class="mb-3">
                <label for="language" class="form-label">交互语种</label>
                <select class="form-select" id="language" required>
                  <option value="zh-CN">中文</option>
                  <option value="en-US">English</option>
                </select>
              </div>
              <div class="mb-3">
                <label for="llmModel" class="form-label">大语言模型</label>
                <select class="form-select" id="llmModel" required>
                  <option value="">请选择大语言模型</option>
                </select>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button type="button" class="btn btn-primary" onclick="saveAgent()">
              保存
            </button>
          </div>
        </div>
      </div>
    </div>

    <script>
      // 初始化页面
      $(document).ready(function () {
        let currentPageNum = 1;
        const pageNum = 10;
        let totalPagesNum = 1;
        let searchKeyword = "";
        loadAgents();
        loadTemplates();
        loadLLMModels();
        loadTtsVoices();
        // 加载智能体列表
        function loadAgents() {
          const params = {
            current: currentPageNum,
            size: pageNum,
            agentName: searchKeyword,
          };
          ajaxGet(`ai/agent/page`, params, "GET", function (data) {
            const agentList = $("#agentList");
            agentList.empty();

            data.records.forEach((agent) => {
              const card = createAgentCard(agent);
              agentList.append(card);
            });

            // 更新分页
            totalPagesNum = Math.ceil(data.total / pageNum);
            updatePagination();
          });
        }

        // 创建智能体卡片
        function createAgentCard(agent) {
          const col = $("<div>").addClass("col-md-6 col-lg-4");

          col.html(`
                <div class="agent-card">
                    <h5>${agent.agentName}</h5>
                    <p class="text-muted">编码: ${agent.agentCode}</p>
                    <p class="text-muted">角色音色: <span id="voice-${
                      agent.id
                    }">加载中...</span></p>
                    <p class="text-muted">交互语种: ${
                      agent.language || "中文"
                    }</p>
                    <p class="text-muted">大语言模型: <span id="model-${
                      agent.id
                    }">加载中...</span></p>
                    <div class="d-flex justify-content-between">
                        <button class="btn btn-sm btn-primary" onclick="showEditModal('${
                          agent.id
                        }')">
                            <i class="bi bi-pencil"></i> 编辑
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteAgent('${
                          agent.id
                        }')">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </div>
                </div>
            `);

          // 加载音色和模型名称
          loadVoiceAndModelNames(agent);

          return col;
        }

        // 加载音色和模型名称
        function loadVoiceAndModelNames(agent) {
          // 加载音色名称
          if (agent.ttsVoiceId) {
            ajaxGet(
              `ai/tts/voice/${agent.ttsVoiceId}`,
              {},
              "GET",
              function (voice) {
                $(`#voice-${agent.id}`).text(voice.name || "默认音色");
              }
            );
          } else {
            $(`#voice-${agent.id}`).text("默认音色");
          }

          // 加载模型名称
          if (agent.llmModelId) {
            ajaxGet(
              `ai/model/config/${agent.llmModelId}`,
              {},
              "GET",
              function (model) {
                $(`#model-${agent.id}`).text(model.modelName || "默认模型");
              }
            );
          } else {
            $(`#model-${agent.id}`).text("默认模型");
          }
        }

        // 更新分页
        function updatePagination() {
          const pagination = $("#pagination");
          pagination.empty();

          // 上一页按钮
          pagination.append(`
                <li class="page-item ${currentPageNum === 1 ? "disabled" : ""}">
                    <a class="page-link" href="#" onclick="changePage(${
                      currentPageNum - 1
                    })">上一页</a>
                </li>
            `);

          // 页码按钮
          for (let i = 1; i <= totalPagesNum; i++) {
            pagination.append(`
                    <li class="page-item ${
                      currentPageNum === i ? "active" : ""
                    }">
                        <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                    </li>
                `);
          }

          // 下一页按钮
          pagination.append(`
                <li class="page-item ${
                  currentPageNum === totalPagesNum ? "disabled" : ""
                }">
                    <a class="page-link" href="#" onclick="changePage(${
                      currentPageNum + 1
                    })">下一页</a>
                </li>
            `);
        }

        // 切换页码
        function changePage(page) {
          if (page < 1 || page > totalPagesNum) return;
          currentPageNum = page;
          loadAgents();
        }

        // 搜索智能体
        function searchAgents() {
          searchKeyword = $("#searchInput").val();
          currentPageNum = 1;
          loadAgents();
        }

        // 加载智能体模板列表
        function loadTemplates() {
          ajaxGet(
            "ai/agent/template/page?current=1&size=100",
            {},
            "GET",
            function (data) {
              const templateSelect = $("#agentTemplate");
              templateSelect
                .empty()
                .append('<option value="">请选择模板</option>');

              data.records.forEach((template) => {
                const option = $("<option>")
                  .val(template.id)
                  .text(template.agentName);
                templateSelect.append(option);
              });
            }
          );
        }

        // 加载大语言模型列表
        function loadLLMModels() {
          ajaxGet(
            "ai/model/config/page?current=1&size=100&modelType=LLM",
            {},
            "GET",
            function (data) {
              const modelSelect = $("#llmModel");
              modelSelect
                .empty()
                .append('<option value="">请选择大语言模型</option>');

              data.records.forEach((model) => {
                const option = $("<option>")
                  .val(model.id)
                  .text(model.modelName);
                modelSelect.append(option);
              });
            }
          );
        }

        // 加载音色列表
        function loadTtsVoices() {
          ajaxGet(
            "ai/tts/voice/page?current=1&size=100",
            {},
            "GET",
            function (data) {
              const voiceSelect = $("#ttsVoice");
              voiceSelect
                .empty()
                .append('<option value="">请选择音色</option>');

              data.records.forEach((voice) => {
                const option = $("<option>").val(voice.id).text(voice.name);
                voiceSelect.append(option);
              });
            }
          );
        }

        // 试听音色
        function previewVoice() {
          const voiceId = $("#ttsVoice").val();
          if (!voiceId) {
            alert("请先选择音色");
            return;
          }

          ajaxGet(
            `ai/tts/voice/demo/${voiceId}`,
            {},
            "GET",
            function (response) {
              const audioBlob = new Blob([response], { type: "audio/wav" });
              const audioUrl = URL.createObjectURL(audioBlob);
              const audio = new Audio(audioUrl);

              audio.onerror = function () {
                alert("音频播放失败");
                URL.revokeObjectURL(audioUrl);
              };

              audio.onended = function () {
                URL.revokeObjectURL(audioUrl);
              };

              audio.play();
            }
          );
        }

        // 加载选中的模板数据
        function loadTemplate(templateId) {
          if (!templateId) return;

          ajaxGet(
            `ai/agent/template/${templateId}`,
            {},
            "GET",
            function (template) {
              $("#agentName").val(template.agentName);
              $("#agentCode").val(template.agentCode);
              $("#systemPrompt").val(template.systemPrompt);
              $("#language").val(template.language);
              $("#llmModel").val(template.llmModelId);
              $("#ttsVoice").val(template.ttsVoiceId);
            }
          );
        }

        // 显示添加模态框
        function showAddModal() {
          $("#modalTitle").text("添加智能体");
          $("#agentForm")[0].reset();
          $("#agentId").val("");
          $("#agentTemplate").val("");
          $("#llmModel").val("");
          $("#ttsVoice").val("zh-CN-XiaoxiaoNeural");
          $("#language").val("zh-CN");
          new bootstrap.Modal($("#agentModal")).show();
        }

        // 显示编辑模态框
        function showEditModal(id) {
          ajaxGet(`ai/agent/${id}`, {}, "GET", function (agent) {
            $("#modalTitle").text(`编辑智能体 - ${agent.agentName}`);
            $("#agentId").val(agent.id);
            $("#agentName").val(agent.agentName);
            $("#agentCode").val(agent.agentCode);
            $("#systemPrompt").val(agent.systemPrompt);
            $("#language").val(agent.language || "zh-CN");
            $("#llmModel").val(agent.llmModelId);
            $("#ttsVoice").val(agent.ttsVoiceId || "zh-CN-XiaoxiaoNeural");
            $("#agentTemplate").val("");
            new bootstrap.Modal($("#agentModal")).show();
          });
        }

        // 保存智能体
        function saveAgent() {
          const agent = {
            id: $("#agentId").val(),
            agentName: $("#agentName").val(),
            agentCode: $("#agentCode").val(),
            systemPrompt: $("#systemPrompt").val(),
            language: $("#language").val(),
            llmModelId: $("#llmModel").val(),
            ttsVoiceId: $("#ttsVoice").val(),
          };

          const method = agent.id ? "PUT" : "POST";
          ajaxPost("ai/agent", agent, method, function (response) {
            bootstrap.Modal.getInstance($("#agentModal")).hide();
            loadAgents();
            alert("保存成功");
          });
        }

        // 删除智能体
        function deleteAgent(id) {
          if (!confirm("确定要删除这个智能体吗？")) return;

          ajaxPost(`ai/agent/${id}`, {}, "DELETE", function (response) {
            loadAgents();
            alert("删除成功");
          });
        }
      });
    </script>
  </body>
</html>
